
/*
 * Copyright (C) 2010 Bitglue. All rights reserved.
 *
 * $Id: AdminInterceptor.java bself $
 */

package com.bitglue.web.admin.webmvc;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

/**
 * AdminInterceptor intercepts all admin console servlet
 * requests and checks for a user in the session.
 * @author Bryan Patrick Self
 */
public class AdminInterceptor extends HandlerInterceptorAdapter {

    protected final Logger log = Logger.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest request,
      HttpServletResponse response, Object handler) {
        if ("/login.do".equals(request.getServletPath()))
            return true;
        if (!check(request, "user"))
            redirect(response, "/admin/login.do");
        return true;
    }

    private boolean check(HttpServletRequest request, String param) {
        try {
            WebUtils.getRequiredSessionAttribute(request, param);
        } catch (IllegalStateException ex) {
            return false;
        }
        return true;
    }

    private void redirect(HttpServletResponse resp, String path) {
        try {
            resp.sendRedirect(path);
        } catch (IOException io) {
            log.error("failed to redirect to " + path, io);
            throw new RuntimeException("failed to redirect to " + path);
        }
    }

}
